package com.alibaba.citrus.ots.price.ability.facade;

import com.alibaba.acm.shaded.com.alibaba.metrics.StringUtils;
import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.citrus.ots.price.repository.CreditQueryRepository;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.EmployeeGetCurrentLoginResponse;
import com.epoch.app.bcots.model.dto.ImportRequest;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.bcots.service.BcOtsService;
import com.epoch.app.otsplatformenhance.enums.RoleCodeEnum;
import com.epoch.app.otspricecenter.api.creditquery.service.CreditQueryService;
import com.epoch.app.otspricecenter.model.dto.BatchQueryCreditRequest;
import com.epoch.app.otspricecenter.model.dto.CreditReponse;
import com.epoch.app.otspricecenter.model.dto.QueryCreditRequest;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: qianlei
 * @create: 2021/10/29 01:08
 */
@Service
@Primary
public class CreditQueryServiceImpl implements CreditQueryService {
    @Autowired
    CreditQueryRepository creditQueryRepository;

    @Autowired
    private BcOtsService bcOtsService;

    private static Log log = Log.getLogger(CreditQueryServiceImpl.class);

    @Override
    @FacadeInvoker(value = "查询信贷余额", errorCode = "OTS-07-006-01-16-002")
    public Result<List<CreditReponse>> queryCredit(BatchQueryCreditRequest batchQueryCreditRequest) {
        QueryCreditRequest queryCreditRequest = batchQueryCreditRequest.getQueryCreditRequestList().get(0);
        if(StringUtils.isBlank(queryCreditRequest.getCustomerCode()) && StringUtils.isBlank(queryCreditRequest.getClientCode())){
           throw new FacadeException("OTS-07-010-01-17-002");
        }
        //如果用户是手动填的客户编码数据，则以这个数据为客户编码查询条件
        if(StringUtils.isNotBlank(queryCreditRequest.getClientCode())){
            queryCreditRequest.setCustomerCode(queryCreditRequest.getClientCode());
        }
        List<CreditReponse> list = new ArrayList<>();

        // 控制角色
        EmployeeGetCurrentLoginResponse currentLoginEmployeeRoles = bcOtsService.employeeGetCurrentLogin();
        if (currentLoginEmployeeRoles != null && StringUtils.isNotBlank(currentLoginEmployeeRoles.getRoleCodes())){
            String roleCodes = currentLoginEmployeeRoles.getRoleCodes();
            if (StringUtils.isBlank(roleCodes) || "[]".equals(roleCodes)){
                return Result.success(list);
            }
            List<String> noPermissionRoleCodeList = Lists.newArrayList(RoleCodeEnum.SALE_MAN.getCode(), RoleCodeEnum.DEPARTMENT_MANAGER.getCode());
            List<String> roles = Lists.newArrayList(roleCodes.replaceAll(" ", "").substring(1, roleCodes.length() - 2).split(","));
            boolean permission = false;
            for (String role : roles) {
                if (!noPermissionRoleCodeList.contains(role)) {
                    permission = true;
                    break;
                }
            }
            if (!permission){
                return Result.success(list);
            }
        }

        try {
            list= creditQueryRepository.queryCreditList(batchQueryCreditRequest);
        }catch (Exception e){
            log.error("查询信贷余额失败 = " + e.getMessage(), e);
        }


        return Result.success(list);
    }
    @Override
    @FacadeInvoker(value = "查询信贷余额", errorCode = "OTS-07-006-01-16-002")
    public Result<CreditReponse> queryCreditBalance(QueryCreditRequest queryCreditRequest){
        BatchQueryCreditRequest batch = new BatchQueryCreditRequest();
        batch.setQueryCreditRequestList(Lists.newArrayList(queryCreditRequest));
        List<CreditReponse> list = creditQueryRepository.queryCreditList(batch, false);
        if (CollectionUtils.isNotEmpty(list)){
            CreditReponse resp = list.get(0);
//            if (resp.getSuccess()){
//                return Result.success(resp);
//            }else {

//                Result result = new Result();
//                result.setResult(resp);
//                result.setSuccess(true);
//                result.setMessage(resp.getMessage());
//                return result;
            return Result.success(resp,resp.getMessage());
//            }
        }
        //todo 先临时这样处理
        return Result.fail(null,"OTS-07-006-01-16-002","查询信贷余额失败！");
    }

}
